/*
 * Copyright 2025 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "fcitxdbusprovider.h"

FcitxDbusProvider::FcitxDbusProvider(QObject *parent) : QObject(parent) {
  registerFcitxQtDBusTypes();
  initServiceWatcher();
  initFcitxControlerProxy();
  connectSignals();
}

void FcitxDbusProvider::initFcitxControlerProxy() {
  proxy_ = new FcitxControllerProxy(service_, path_,
                                    QDBusConnection::sessionBus(), this);
}

void FcitxDbusProvider::destroyFcitxControlerProxy() {
  if (proxy_ == nullptr) {
    return;
  }

  delete proxy_;
  proxy_ = nullptr;
}

void FcitxDbusProvider::initServiceWatcher() {
  watcher_ =
      new QDBusServiceWatcher(service_, QDBusConnection::sessionBus(),
                              QDBusServiceWatcher::WatchForRegistration |
                                  QDBusServiceWatcher::WatchForUnregistration,
                              this);
}

void FcitxDbusProvider::connectSignals() {
  QObject::connect(watcher_, &QDBusServiceWatcher::serviceRegistered, this,
                   [this]() {
                     initFcitxControlerProxy();
                     emit fcitxDbusServiceEnabled();
                   });

  QObject::connect(watcher_, &QDBusServiceWatcher::serviceUnregistered, this,
                   [this]() {
                     destroyFcitxControlerProxy();
                     emit fcitxDbusServiceDisabled();
                   });
}

FcitxControllerProxy *FcitxDbusProvider::dbusProxy() const { return proxy_; }
